package org.flashbrighton.as3bots.controllers 
{
	import flash.display.Sprite;
	import flash.events.*;
	import flash.utils.Timer;
	
	import org.flashbrighton.as3bots.events.MatchEndEvent;
	import org.flashbrighton.as3bots.models.*;
	import org.flashbrighton.as3bots.views.*;
	
	public class MatchController extends EventDispatcher
	{
		public static var MAX_TIME:int = 80;
		
		private var _model:GameModel;
		private var _view:GameView;
		private var _timer:Timer;
		
		
		public function MatchController(model:GameModel, view:GameView) 
		{
			_model = model;
			_view = view;
			init();
		}
		
		
		private function init():void 
		{
			_timer = new Timer(1000, MAX_TIME);
			_timer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimeEnd);
		}
		
		
		public function update():void
		{
			removeDeadBots();
			removeCollectedGems();
			removeExplodedBombs();
			checkForWinner();
		}
		
		private function removeCollectedGems():void
		{
			for each (var gem:GemModel in _model.gemList)
			{
				if (gem.isCollected)
				{
					_model.removeGem(gem);
				}
			}
		}		
		
		public function removeDeadBots():void 
		{
			for each (var bot:BotModel in _model.botList)
			{
				if (bot.energy < 0)
				{
					_model.removeBot(bot);
				}
			}
		}
		
		private function removeExplodedBombs():void
		{
			for each (var bomb:BombModel in _model.bombList)
			{
				if (bomb.hasExploded)
				{
					_model.removeBomb(bomb);
				}
			}
		}		
		
		public function checkForWinner():void
		{
			if (_model.botList.length == 1)
			{
				setWinner(_model.botList[0]);
			}
		}
		
		
		public function onTimeEnd(e:TimerEvent):void 
		{			
			var strongest:BotModel = _model.botList[0];
			
			for each (var botModel:BotModel in _model.botList) 
			{
				if (botModel.energy > strongest.energy) strongest = botModel;
			}
			
			setWinner(strongest);
		}
		
		
		public function setWinner(botModel:BotModel):void
		{
			_view.alert.show(botModel.bot.botName.toUpperCase() + "\nWINS!");
			dispatchEvent(new MatchEndEvent(botModel.bot));
		}
		
		
		public function get timer():Timer 
		{ 
			return _timer; 
		}
		
	}

}